package io.kiki.sba.registry.store.api.config;

import io.kiki.sba.registry.store.api.meta.RecoverConfigRepository;
import io.kiki.sba.registry.store.api.spring.SpringContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;

import java.util.Set;


public class DefaultCommonConfigBean implements DefaultCommonConfig {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultCommonConfigBean.class);
    private static final String ALL_KEY = "ALL";
    @Value("${nodes.localDataCenter:DefaultDataCenter}")
    private String dataCenter;
    @Value("${nodes.clusterId:}")
    private String clusterId;
    @Value("${persistence.profile.active:jdbc}")
    private String persistenceProfileActive;
    @Value("${nodes.recoverClusterId:}")
    private String recoverClusterId;
    @Autowired
    private RecoverConfigRepository recoverConfigRepository;

    @Override
    public String getDefaultClusterId() {
        if (StringUtils.isNotBlank(clusterId)) {
            return clusterId;
        }
        return dataCenter;
    }

    private String getDefaultRecoverClusterId() {
        if (StringUtils.isNotBlank(recoverClusterId)) {
            return recoverClusterId;
        }
        return getDefaultClusterId();
    }

    @Override
    public String getClusterId(String table) {
        Set<String> keys = recoverConfigRepository.queryKey(table);
        String recoverClusterId = getDefaultRecoverClusterId();
        if (!CollectionUtils.isEmpty(keys) && keys.contains(ALL_KEY)) {
            LOG.info("[GetClusterId]propertyTable:{}, clusterId:{}", table, recoverClusterId);
            return getDefaultRecoverClusterId();
        }
        return getDefaultClusterId();
    }

    @Override
    public String getClusterId(String table, String key) {
        if (StringUtils.isEmpty(table)) {
            throw new IllegalArgumentException("tableName is empty.");
        }
        if (StringUtils.isEmpty(key)) {
            return getClusterId(table);
        }

        Set<String> keys = recoverConfigRepository.queryKey(table);
        String recoverClusterId = getDefaultRecoverClusterId();
        if (!CollectionUtils.isEmpty(keys) && keys.contains(key)) {
            LOG.info("[GetClusterId]propertyTable:{}, propertyKey:{}, clusterId:{}", table, key, recoverClusterId);
            return recoverClusterId;
        }

        return getDefaultClusterId();
    }

    @Override
    public boolean isRecoverCluster() {
        return !StringUtils.equals(getDefaultClusterId(), getDefaultRecoverClusterId());
    }

    @Override
    public String getRecoverClusterId() {
        return recoverClusterId;
    }


    public boolean isJdbc() {
        return !SpringContext.META_STORE_API_RAFT.equals(persistenceProfileActive);
    }
}
